package com.otachn.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.otachn.utiils.PropertiesUtil;

import static com.otachn.utiils.PropertiesUtil.getPropertyFromFile;
import static com.otachn.utiils.PropertiesUtil.setFile;;

public class DBTool {
	
	private final String username, password, driver, url;
	private Connection conn;
	private static Logger logger = Logger.getLogger(PropertiesUtil.class);
	private DBTool(){
		
		setFile("jdbc.properties");
		username = getPropertyFromFile("jdbc.username");
		password = getPropertyFromFile("jdbc.password");
		url = getPropertyFromFile("jdbc.url");
		driver = getPropertyFromFile("jdbc.driver");
		
		try{
			Class.forName(driver);
			conn=DriverManager.getConnection(url,username,password);
			logger.info("db connected.");;
		}catch(Exception e){
			logger.error("DBTool: " + e.getMessage());
		}
	}
	
	public Connection getConnection(){
		return conn;
	}
	
	public static DBTool newInstance(){
		return new DBTool();
	}
	
	public void closeConn(Connection conn){
		if(conn!=null){
			try{
				conn.close();
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				try{
					conn.close();
				}catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
	}
	
	public void closePstmt(PreparedStatement pstmt){
		if(pstmt!=null){
			try{
				pstmt.close();
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				try{
					pstmt.close();
				}catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
	}
	
	public void closeResultSet(ResultSet rs){
		if(rs!=null){
			try{
				rs.close();
			}catch(SQLException e){
				e.printStackTrace();
			}finally{
				try{
					rs.close();
				}catch(SQLException e){
					e.printStackTrace();
				}
			}
		}
	}
}
